package com.acwer.oa.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.acwer.oa.web.utils.JwtUtils;

import io.jsonwebtoken.Claims;

@Component
public class JwtInterceptor implements HandlerInterceptor {
   
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("经过了拦截器");
        //无论如何都放行。具体能不能操作还是在具体的操作中去判断。	
        //拦截器只是负责把有请求头中包含token的令牌进行一个解析验证。
        String header = request.getHeader("Authorization");
        if(header!=null && !"".equals(header)){
            //如果有包含有Authorization头信息，就对其进行解析
            if(header.startsWith("Bearer ")){
                //得到token
                String token = header.substring(7);
                //securityUtil.logInAs(token);
                //对令牌进行验证
                try {
                    Claims claims = JwtUtils.getTokenClaim(token);
                    String roles = (String) claims.get("roles");
                    String account=claims.getSubject();
                    if(JwtUtils.isTokenExpired(claims.getExpiration())){
                    	throw new Exception("密码已过期！");
                    }
//                    System.out.println("roles:"+roles+",account:"+account);
                    request.setAttribute("account", account);
                    request.setAttribute("roles", roles);
                }catch (Exception e){
                    throw new RuntimeException("令牌不正确！");
                }
            }
        }
        return true;
    }
}